﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：吕海乐 
    //
    // 文件名：HospitalMange.aspx.cs
    // 文件功能描述：医疗机构管理
    // 创建标识：吕海乐2009-05-25
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.Model.Enum;

namespace HZ.DrugTrade.Web.Admin.SystemManage
{
    public partial class HospitalMange : BasePage
    {
        public HospitalMange()
        {
            this.ModuleNo = Module.系统管理.ToString();
            this.PageOperateType = OperateType.医疗机构管理.ToString();
        }

        IBLL_Hospital ih = Factory.BLL_Hospital();
        IBLL_User iu = Factory.BLL_User();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetBind();

                //设置下拉框Enable
                GetDefaultAreaString();

                if (CurrentAccount.GetUser().UserID == "ROOT")
                {
                    this.hzbtnRandom.Enabled = true;
                }
                else
                {
                    this.hzbtnRandom.Enabled = false;
                    this.hzbtnRandom.Visible = false;
                }
            }
        }

        /// <summary>
        /// 绑定所有医疗机构
        /// </summary>
        private void SetBind()
        {
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalCount;
            Model.Query.Hospital qHospital = new HZ.DrugTrade.Model.Query.Hospital();
            qHospital.HospitalName = txtHospitalName.Text.Trim();
            qHospital.HospitalID = txtHospitalID.Text.Trim().ToUpper();
            qHospital.AreaID = GetAreaID();
            if (this.drpIsUing.Text == "已启用")
            {
                qHospital.Append = " NVL(IsUsing,0)=1 ";
               // qHospital.Append = " isUsing =1 ";
            }
            else if (this.drpIsUing.Text=="未启用")
            {
                qHospital.Append = " NVL(IsUsing,0)=0 ";
               // qHospital.Append = " IsUsing =0 ";
            }
            if (!string.IsNullOrEmpty(this.ddlCountyOver.SelectedValue))
            {
                qHospital.CountyOver = this.ddlCountyOver.SelectedValue;
                //if (this.ddlCountyOver.SelectedValue == "1")//县级以上 add by zdc
                //{
                //    qHospital.CountyOver = this.ddlCountyOver.SelectedValue;
                //}
                //else
                //{
                //    qHospital.Append = " CountyOv='基层'";
                //}
            }



            qHospital.SortFields = " hospitalid";
            IList<Hospital> lstHospital = ih.GetHospitalByWhere(qHospital, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            AspNetPager1.RecordCount = totalCount;
            gvwHospital.DataSource = lstHospital;
            gvwHospital.DataBind();
        }

        /// <summary>
        /// 获取地区查询条件 AreaID
        /// </summary>
        /// <returns></returns>
        private string GetAreaID()
        {
            string areaId = "";

            //首次进入使用当前用户所在区域ID
            areaId = CurrentAccount.GetUser().Org.Area.AreaID;

            //优先获取区县，其次城市，再次省份
            if (new Common.ConvertHelper(Request.Form["ctl00$ContentPlaceHolder1$ddlCountry"]).String != Constants.ALL_ITEM_VALUE)
            {
                areaId = Request.Form["ctl00$ContentPlaceHolder1$ddlCountry"];
            }
            else
            {
                if (new Common.ConvertHelper(Request.Form["ctl00$ContentPlaceHolder1$ddlCity"]).String != Constants.ALL_ITEM_VALUE)
                {
                    areaId = Request.Form["ctl00$ContentPlaceHolder1$ddlCity"];
                }
                else if (new Common.ConvertHelper(Request.Form["ctl00$ContentPlaceHolder1$ddlProvice"]).String != Constants.ALL_ITEM_VALUE)
                {
                    areaId = Request.Form["ctl00$ContentPlaceHolder1$ddlProvice"];
                }

            }
            return areaId;
        }

        /// <summary>
        /// 获取默认选中的地区编号串
        /// 供JS函数使用
        /// </summary>
        /// <returns></returns>
        protected string GetDefaultAreaString()
        {
            //默认城市 江苏省 320000
            string defaultProvince = "150000";
            string defaultCity = "";
            //
            string strArea = "";

            //获取当前用户所在区域
            IBLL_Area areaCtrl = Factory.BLL_Area();
            Area area = areaCtrl.GetArea(CurrentAccount.GetUser().Org.Area.AreaID);

            //如果是市级中心机构，则默认选中具体城市
            if (area.FatherAreaID != "0")
            {
                defaultProvince = area.FatherAreaID;
                defaultCity = area.AreaID;
            }
            else
            {
                defaultProvince = area.AreaID;
            }

            //显示默认地区，范围之外的内容禁止选择
            strArea += "," + "\"" + defaultProvince + "\"";
            this.ddlProvice.Enabled = false;
            if (!string.IsNullOrEmpty(defaultCity))
            {
                strArea += "," + "\"" + defaultCity + "\"";
                this.ddlCity.Enabled = false;
            }
            else if (!string.IsNullOrEmpty(Request.Form["ctl00$ContentPlaceHolder1$ddlCity"]))
            {
                strArea += "," + "\"" + Request.Form["ctl00$ContentPlaceHolder1$ddlCity"] + "\"";
            }

            if (!string.IsNullOrEmpty(Request.Form["ctl00$ContentPlaceHolder1$ddlCountry"]))
            {
                strArea += "," + "\"" + Request.Form["ctl00$ContentPlaceHolder1$ddlCountry"] + "\"";
            }

            return strArea;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            SetBind();
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            SetBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            //HZ.Web.WebUtil.RedirectByScript("HospitalAdd.aspx");
            Response.Redirect("HospitalAdd.aspx");
        }

        /// <summary>
        /// 删除医疗机构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwHospital_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                string hID = e.CommandArgument.ToString();
                Hospital hospital = new Hospital();
                hospital.HospitalID = hID;
                int flag = ih.DeleteHospital(hospital);
                if (flag == 0)
                {
                    PageError("删除失败！", this.ReturnUrl);
                }
                else if (flag == 1)
                {
                    PageInfo("删除成功！",this.ReturnUrl);
                }
                else if (flag == 2)
                {
                    PageError("正在使用无法删除！",this.ReturnUrl);
                }
            }
            if (e.CommandName == "Update")
            {
                Response.Redirect("HospitalInfo.aspx?hID="+e.CommandArgument.ToString()+"");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hzbtnRandom_Click(object sender, EventArgs e)
        {

            int totalCount;
            //Model.Query.HospitalInfo qHospital = new HZ.DrugTrade.Model.Query.HospitalInfo();
            //qHospital.HospitalName = txtHospitalName.Text.Trim();
            //qHospital.AreaID = GetAreaID();
            IList<Model.HospitalInfo> lst = ih.GetAllUnInitializeHopialInfo("", 1, 0, out totalCount);

            #region 医疗机构密码随机初始化
            if (lst.Count > 0)
            {
                List<User> userIds = new List<User>();
                System.Data.DataTable dt = new System.Data.DataTable();
                dt.Columns.Add(new System.Data.DataColumn("UserID", Type.GetType("System.String")));
                dt.Columns.Add(new System.Data.DataColumn("UserName", Type.GetType("System.String")));
                dt.Columns.Add(new System.Data.DataColumn("UserPassword", Type.GetType("System.String")));
                Random rnd = new Random(DateTime.Now.Millisecond);
                string temp = "0";
                foreach (Model.HospitalInfo item in lst)
                {
                    if (!string.IsNullOrEmpty(item.HospitalID)
                        //乡镇卫生院
                        && string.Compare(item.HospitalID,"H5000")>0
                        )
                    {
                        User model = new User();
                        System.Data.DataRow dr = dt.NewRow();
                        dr["UserID"] = item.HospitalID;
                        dr["UserName"] = item.HospitalName;
                        model.UserID = item.HospitalID;
                        do
                        {
                            model.UserPassword = rnd.Next(100000, 999999).ToString();
                        }
                        while (temp == model.UserPassword);
                        temp = model.UserPassword;

                        dr["UserPassword"] = model.UserPassword;
                        userIds.Add(model);
                        dt.Rows.Add(dr);
                    }

                }
                if (userIds.Count > 0)
                {
                    if (iu.InitPassword(userIds))
                    {
                        HZ.Excel.ExcelHelper.ExportDataForWeb(dt, this.GridView1);
                    }
                    else
                    {
                        HZ.Web.WebUtil.Alert("密码初始化失败！");
                    }
                }
            }
            else
            {
                HZ.Web.WebUtil.Alert("没有发现医疗机构信息！");
            }
            #endregion 

            #region 根据医疗机构上年度产品支出总额初始化密码
            //if (lst.Count > 0)
            //{

            //    List<User> userIds = new List<User>();
            //    foreach (Model.HospitalInfo item in lst)
            //    {
            //        if (!string.IsNullOrEmpty(item.HospitalID))
            //        {
            //            User model = new User();
            //            model.UserID = item.HospitalID;

            //            if (!string.IsNullOrEmpty(item.Expenditure) && HZ.Fun.IsFloat(item.Expenditure))
            //            {
            //                model.UserPassword = item.Expenditure.Trim().Split('.')[0];
            //                //model.UserPassword = item.Expenditure.Trim();
            //            }
            //            else
            //            {
            //                model.UserPassword = Constants.USER_DEFAULT_PWS;
            //            }
            //            userIds.Add(model);
            //        }
                  
            //    }
            //    if (userIds.Count>0)
            //    {
            //        if (iu.InitPassword(userIds))
            //        {
            //            HZ.Web.WebUtil.Alert("密码初始化成功！");
            //        }
            //        else
            //        {
            //            HZ.Web.WebUtil.Alert("密码初始化失败！");
            //        }
            //    }
            //}
            //else
            //{
            //    HZ.Web.WebUtil.Alert("没有发现医疗机构信息！");
            //}
            #endregion 
        }

        protected void hzbtnExcelImport_Click(object sender, EventArgs e)
        {
            int totalCount;
            HZ.DrugTrade.Model.Query.Hospital qHospital = new HZ.DrugTrade.Model.Query.Hospital();
            
            qHospital.HospitalName = txtHospitalName.Text.Trim();
            qHospital.HospitalID = txtHospitalID.Text.Trim().ToUpper();
            qHospital.AreaID = GetAreaID();
            if (this.drpIsUing.Text == "已启用")
            {
                qHospital.Append = " NVL(IsUsing,0)=1 ";
                // qHospital.Append = " isUsing =1 ";
            }
            else if (this.drpIsUing.Text == "未启用")
            {
                qHospital.Append = " NVL(IsUsing,0)=0 ";
                // qHospital.Append = " IsUsing =0 ";
            }
            if (!string.IsNullOrEmpty(this.ddlCountyOver.SelectedValue))
            {
                qHospital.CountyOver = this.ddlCountyOver.SelectedValue;
                //if (this.ddlCountyOver.SelectedValue == "1")//县级以上 add by zdc
                //{
                //    qHospital.CountyOver = this.ddlCountyOver.SelectedValue;
                //}
                //else
                //{
                //    qHospital.Append = " CountyOv='基层'";
                //}
            }



            qHospital.SortFields = " hospitalid";
            string where = HZ.DrugTrade.DAL2.DAL_Helper.GetWhereCondition<HZ.DrugTrade.Model.Query.Hospital>(qHospital, true);
            string sql = string.Format(@"select AreaName 地区名称,
                                   FatherAreaID 盟市编号,
                                   HospitalID 医疗机构编号,
                                   AreaID 地区编号,
                                   HospitalName 医疗机构名称,
                                   HospitalAddress 医疗机构地址,
                                   ContactPerson 联系人,
                                   ContactTel 联系电话, 
                                   Levels 等级,
                                   LevelDetail 等次,
                                   Nature 医疗机构性质, 
                                   CountyOv 是否县级以上,
                                   updateTime 修改时间,
                                   IsUsing 是否启用
                              from View_HospitalArea WHERE 1=1 {0}", where);

            //System.Data.DataTable dt = ih.GetAllHopialInfo2(qHospital, 1, 0, out totalCount);
            //modify by xy 20121009
            //IList<Hospital> lstHospital = ih.GetHospitalByWhere(qHospital, 1, 0, out totalCount);
            //System.Data.DataTable dt = HZ.Data.ModelConvert.GetDataTableFromModel(lstHospital);
            HZ.DrugTrade.BLL.ExcelHelper.ExportByWeb(HZ.Data.DbHelperFactory.Create().ExecuteTable(sql), "", "医疗机构信息.xls");
            //HZ.Excel.ExcelHelper.ExportDataForWeb(dt, this.grvExcelImport);
        }

    


     
  
    }
}
